<?php
// +----------------------------------------------------------------------
// | 店铺购物车
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Validate;

class ShopCart extends Model
{
	use \base\model\ModelTrait;
	
	/**
     * 获取购物车列表
     * @return type
     */
	public function getCartList($uid,$giveType=1)
    {
		$model = new self();
        $model = $model->alias('a');
        $model = $model->leftJoin("goods b",'b.id = a.goods_id');
        $model = $model->where('a.uid', $uid);
        $model = $model->where('a.is_pay', 0);
        $model = $model->where('a.is_del', 0);
        $model = $model->where('a.is_new', 0);
        $model = $model->where('b.give_type',$giveType == 1 ? 1 : 0);
        $model = $model->where('a.cart_num','>',0);
		$model = $model->order('a.add_time','DESC');
        $model = $model->field('a.id,a.goods_id,a.cart_num,a.specs_id,a.add_time,b.give_type');
        $cartList = $model->select();
        $data = [];
        foreach($cartList as $key => $cart){
        	if( $goodsInfo = model('Goods')->details($cart['goods_id'],$cart['specs_id'])  ){
        		$cart['goodsInfo']  = $goodsInfo;
        		$data[] = $cart;
        	}
        }
        return $data;
    }
	
	
	/**
     * 设置购物车-加
     * @param type $data
     * @return type
     */
	public function setCartInc($uid,$goods_id=0,$specs_id=0,$cart_num=1,$is_new=0,$seckill_id=0)
    {
		$cart = self::where('uid', $uid);
		$cart = $cart->where('goods_id', $goods_id);
		$cart = $cart->where('specs_id', $specs_id);
		$cart = $cart->where('seckill_id', $seckill_id);
		$cart = $cart->where('is_new', $is_new ? $is_new : 0);
		$cart = $cart->where('is_pay', 0);
		$cart = $cart->where('is_del', 0);
		$cart = $cart->field('is_del,add_time', true);
		$cart = $cart->lock(true)->find();
		
		//当前购物车数量
		if($cart){
			if ( $is_new ){
	            $cart->cart_num = $cart_num;
	        } else {
	        	$cart->cart_num = $cart_num = bcadd($cart_num, $cart->cart_num ?: 0, 0);
	        }
		}
		
		//效验
        if ($seckill_id) {
            if ( !$seckillinfo = model('GoodsSeckill')->getValidSeckill($seckill_id) ){
            	throw new \think\Exception('秒杀已结束！');
            }
			//用户历史购买数
			$userBuyCount = model('OrderCart')->getUserSeckillBuyNum($uid,$seckill_id);
            if ($userBuyCount === false){
            	throw new \think\Exception( '该商品已存在您的订单中，请完成支付后再继续下单！');
            }
			//限购判断
			if ($seckillinfo['seckill_num'] <= $userBuyCount) {
            	throw new \think\Exception('您已购买过该产品，每人限购' . $seckillinfo['seckill_num'] . '件');
            } 
			if ($seckillinfo['seckill_num'] < $cart_num + $userBuyCount) {
            	throw new \think\Exception('每人限购' . $seckillinfo['seckill_num'] . '件');
            }
			//库存判断
			if (model('GoodsSeckill')->getStock($seckill_id) < $cart_num){
				throw new \think\Exception('该产品库存不足');
			}
        }else{
        	if (!$goods = model('Goods')->details($goods_id)){
        		throw new \think\Exception('该产品已下架或删除！');
        	}
        	$specsInfo = '';
        	foreach($goods->specs_list as $key => $specs){
        		if($specs['id'] == $specs_id){
        			$specsInfo = $specs;
        		}
        	}
        	if(!$specsInfo){
        		throw new \think\Exception('该规格不存在或已下架！');
            }
            if($specsInfo['stock'] < $cart_num){
            	throw new \think\Exception('该规格库存不足！');
            }
        }
		
		// 保存
        if ( $cart  ) {
			if ($seckillinfo && $seckillinfo['seckill_num'] < $cart_num) {
				throw new \think\Exception('每人限购' . $seckillinfo['seckill_num'] . '件');
            }
            $cart->save();
            return $cart;
        } else {
        	$shop_id = $goods->shop_id;
        	$data = compact('uid','shop_id','goods_id', 'specs_id', 'cart_num','seckill_id','is_new');
        	$res = self::isUpdate(false)->data($data,true)->save();
        	return $this;
        }
    }
    
	
	
	/**
     * 设置购物车-减
     * @param type $data
     * @return type
     */
	public function setCartDec($uid,$goods_id=0,$specs_id=0,$cart_num=1,$is_new=0,$seckill_id=0)
    {
		$cart = self::where('uid', $uid);
		$cart = $cart->where('goods_id', $goods_id);
		$cart = $cart->where('specs_id', $specs_id);
		$cart = $cart->where('seckill_id', $seckill_id);
		$cart = $cart->where('is_new', $is_new);
		$cart = $cart->where('is_pay', 0);
		$cart = $cart->where('is_del', 0);
		$cart = $cart->field('is_del,add_time', true);
        if ( $cart = $cart->find() ) {
            if ($is_new){
                $cart->cart_num = $cart_num;
            } else {
                $cart->cart_num = $cart->cart_num>= $cart_num ? ($cart->cart_num - $cart_num) : 0;
            }
			$cart->save();
        }
		return $cart;
    }
	
	/**
     * TODO 修改购物车数量
     * @return StoreCart|bool
     * @throws \think\Exception
     */
    public  function changeUserCartNum(int $uid,int $id,int $type)
    {
        if ( !$cart = self::where('uid', $uid)->get($id) ){
        	throw new \think\Exception('购物车不存在！');
		}
		
		$stock = 0;
        if ($cart['seckill_id']) {
            //TODO 获取秒杀产品的库存
            $stock = model('GoodsSeckill')->where('id', $cart['seckill_id'])->value('seckill_stock');
            // TODO 秒杀产品限购
	        if ($cart['seckill_id']) {
	            $seckillinfo = model('GoodsSeckill')->getValidSeckill($cart['seckill_id']);
	            if ($seckillinfo === false){
	            	throw new \think\Exception('该产品已下架或删除!');
	            }
				$userBuyCount = model('OrderCart')->getUserSeckillBuyNum($uid,$cart['seckill_id']);
				if ($seckillinfo['seckill_num'] <= $userBuyCount) {
					throw new \think\Exception('您已购买过该产品，每人限购' . $seckillinfo['seckill_num'] . '件');
	            } 
				if ($userBuyCount  + $cartNum > $seckillinfo['seckill_num'] ) {
					throw new \think\Exception('每人限购'.$seckillinfo['seckill_num'].'件');
	            }					
	        }
        } else {
            //TODO 获取普通产品的库存
           	$stock = model('Goods')->details($cart['goods_id'],$cart['specs_id'])['stock'] ?? 0;
        }
		
		//减
		if($type==2 && $cart['cart_num']<2){
			throw new \think\Exception('购物车数量最少为1！');
		}
		//加
		if($type==1 && ($cart['cart_num']+1) > $stock ){
			throw new \think\Exception('库存不足！');
		}
		
		//保存
		$cart	->cart_num =$type ==1 ? ( $cart['cart_num'] +1 ) : ($cart['cart_num'] -1);
		$res = $cart->save();
		
		//返回新数量
		return $cart->cart_num;
    }
	
	
	//删除用户购物车
	public static function removeUserCart($uid, $ids)
    {
        return self::where('uid', $uid)->where('id', 'in', $ids)->delete();
        //return self::where('uid', $uid)->where('id', 'in', $ids)->update(['is_del' => 1]);
    }
	
	//清空用户购物车
	public static function emptyUserCart($uid)
    {
        return self::where('uid', $uid)->delete();
        //return self::where('uid', $uid)->update(['is_del' => 1]);
    }
	
	//获取用户购物车数量
	public static function getUserCartNum($uid)
    {
		$result = self::getUserGoodsCartList($uid);
		return [
			"cart_num"=> count($result),
			"goods_num"=> array_sum(array_column($result, 'cart_num')),
			"toal_oid_price"=> array_sum(array_column($result, 'price')),
			"toal_sale_price"=> array_sum(array_column($result, 'sale_price')),
		];
    }
	
	
	/**
     * 获取用户商品购物车数量
     * @param type $data
     * @return type
     */
	public static function getUserGoodsCartNum($uid, $goodsId=0,$seckill_id=0,$specs_id='')
    {
      	$model = self::where('uid', $uid);
		$model = $model->where('goods_id', $goodsId);
		$model = $model->where('seckill_id', $seckill_id);
		$model = $model->where('specs_id', $specs_id);
		$model = $model->where('is_pay', 0);
		$model = $model->where('is_del', 0);
		$model = $model->where('is_new', 0);
		return $model->value('cart_num');
    }
	
	/**
    * 获取用户商品购物车列表
    * @param type $data
    * @return type
    */
	public  function getUserGoodsCartList($uid,$cartIds=-1,$userInfo)
    {
    	//当前店铺信息
		$shopId = request()->shopId ?? 0;
		
    	//获取购物车
		$model = new self();
        $model = $model->alias('a');
        $model = $model->where('a.uid', $uid);
        $model = $model->where('a.is_pay', 0);
        $model = $model->where('a.is_del', 0);
        $model = $model->where('a.cart_num','>',0);
		if ($cartIds!=-1) $model = $model->where('a.id', 'in', $cartIds);
		$model = $model->order('a.add_time','DESC');
        $model = $model->field('a.id,a.shop_id,a.goods_id,a.seckill_id,a.specs_id,a.cart_num');
        $model = $model->field('a.type,a.is_pay,a.is_new,a.add_time');
        if ( ! $list = $model->select() ){
        	throw new \think\Exception('购物车信息异常，请重新进入');
        }
		
		$valid = [];
        foreach ($list as $k => $cart) {
			//商品不存在- 删除当前购物车
			$goods =  model('Goods')
				->setShop($shopId)
    			->setUser($uid)
    			->details($cart['goods_id'],$cart['specs_id']);
			if (! $goods ) {
                self::where('id', $cart['id'])->update(['is_del' => 1]);
                throw new \think\Exception('商品已失效，请重新进入！');
            } 
			//秒杀产品不符合或秒杀活动已结束 - 删除当前购物车
			if( $cart['seckill_id'] && $cart['seckill_id'] != $goods['seckill_id'] ){
				self::where('id', $cart['id'])->update(['is_del' => 1]);
				throw new \think\Exception($goods['name'].'-已失效');
			}
			//规格 -- 库存不足 - 更新当前库存
			if( !$goods['stock'] || $goods['stock'] < $cart['cart_num'] ) {
				self::where('id', $cart['id'])->update(['cart_num' => $goods['stock']]);
				throw new \think\Exception('库存不足'.$cart['cart_num'].' , 已自动更新！');
            }
			
            //获取购物车商品价格
            $cart['cost_price'] = $goods['cost_price'];
            $cart['price'] = $goods['price'];
        	$cart['sale_price'] = $goods['sale_price'];
        	$cart['sale_old_price'] = $goods['sale_old_price'];
			$cart['specs_name'] = $goods['specs_name'];
			$cart['freight_id'] = $goods['freight_id'];
			$cart['give_type'] = $goods['give_type'];
				
			//商品信息
			$cart['goods'] = $goods->toArray();
			
			//店铺信息 
			$cart['shop'] = model('shop')
				->where('id',$goods['shop_id'])
				->field('id,name,phone,img')
				->find();
			
			//录入												
            $valid[] = $cart;
        }
        return $valid;
    }

}
